<template>
    <div class="topic_cont flex_column_between relative" style="padding-bottom: 2.5rem; position: relative" ref="boxfull" v-loading="loading">
        <h5 class="title">选择单词</h5>    
        <div class="flex flex-1" style="width: 100%; min-height: 0;">
            <div class="flex" style="width: 100%; border-radius: 1rem; flex-direction: column; min-height: 0; box-shadow: 0 0 10px rgba(0,0,0,0.1);">
                <div class="flex" style="justify-content: center; padding: 1rem 0; font-size: 2rem; gap: 1rem;">
                    <div v-for="(item, index) in letters" :key="index" @click="scrollto(item)" style="cursor: pointer;">{{item}}</div>
                </div>
                <div ref="scrollBox" style="flex: 1; overflow: auto;">
                    <template v-for="(item, index) in vocabularyItems">
                        <div style="padding: 1rem 3rem; background-color: #e6e6e6; margin-bottom: 2rem; font-size: 1.5rem;" :id="item.letter">{{item.letter}}</div>
                        <div class="flex" style="padding: 0 2rem; margin-bottom: 2rem; align-items: flex-start; align-content: flex-start; flex-wrap: wrap; gap: 2rem; min-height: 0; flex: 1;">
                            <div v-for="(word, _idx) in item.list" class="word-item" :class="{'word-item-active': selectedVocabularys.findIndex(row => row.id == word.id) > -1}" @click="chooseVocabularyFun(word)">{{word.word}}</div>
                        </div>
                    </template>
                    <empty v-if="!loading && !vocabularyItems.length" type="1" text="暂无已学单词" />
                </div>
                <div class="flex_column_between" style="width: 100%; padding: 1rem 2rem;">
                    <div class="flex-1"></div>
                    <div style="display: flex; width: 100%; align-items: center; justify-content: space-between;">
                        <div style="font-size: 2rem;cursor: pointer;" @click="showVocabularys">已选择单词<span style="color: #019E69;"> {{ selectedVocabularys.length }} </span>个</div>
                        <el-button style="width: 12rem;font-size:2rem;padding: 1.1rem 3rem;"  type="primary" >  
                            <div class="flex_c_c cur" v-loading="confirmLoading" @click="confirmChoose">
                                <img style="margin-right: 12px;width: 3rem" src="@/assets/img/zt.png" />确认
                            </div> 
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <bear_dialogVue
            ref="bearDialog"
            :width="'65%'"
            :height="'70vh'"
            :isUserFooter="false"
        >
            <template #topControl>
                <div class="blod" style="font-size: 2.6rem">已选择单词</div>
            </template>

            <div style="flex: 1; overflow: auto;">
                <div class="flex" style="padding: 0 2rem; margin-bottom: 2rem; align-items: flex-start; align-content: flex-start; flex-wrap: wrap; gap: 2rem; min-height: 0; flex: 1;">
                    <div v-for="(item, _idx) in selectedVocabularys" class="word-item word-item-active">
                        {{item.word}}
                        <i class="el-icon-close" title="移除" @click="removeSelectedWord(_idx)"></i>
                    </div>

                    <empty type="1" text="暂无已选单词" v-if="selectedVocabularys.length === 0" />
                </div>
            </div>
        </bear_dialogVue>
    </div>
</template>

<script>
// 选择词汇
import { exerciseInfo, join } from '@/api/articleExercise.js'
import { courseWordItems, getDictWordssBykeyword } from '@/api/course.js'
import { learnRecordWord } from '@/api/learn.js'
import bear_dialogVue from '@/views/components/bear_dialog.vue'
import prependSelect from "@/components/select/prepend.vue";
export default {
    components: {
        bear_dialogVue,
        prependSelect
    },
    data() {
        return {
            loading: false,
            searchLoading: false,
            confirmLoading: false,
            exerciseId: '',
            courseId: '',
            course: {},
            exercise: {},
            vocabularyItems: [],
            userId: 0,
            chooseArticle: 0,
            selectedVocabularys: [],
            letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
            search: {
                ids: [],
                loading: false,
                dataItems: []
            },
            learnId: 0,
            appointmentId: 0
        }
    },
    mounted() {
        this.userId = this.$route.query.userId || 0
        this.exerciseId = this.$route.query.exerciseId
        this.learnId = this.$route.query.learnId || 0
        this.appointmentId = this.$route.query.appointmentId || 0
        this.course = { 
            id: this.$route.query.courseId 
        };

        if (this.exerciseId) {
            this.getExercise();
        }else {
            this.getVocabularyList()
        }
        
    },
    methods: {
        getExercise() {
            this.loading = true
            exerciseInfo({ id: this.exerciseId, userId: this.userId }).then(res => {
                this.loading = false
                if (res.error == 0) {
                    this.exercise = res.data
                    this.course = res.data.course
                    this.getVocabularyList()
                }
            }).finally(() => {
                this.loading = false
            })
        },
        // 获取文章列表
        getVocabularyList() {
            this.loading = true
            if (this.learnId) {
                learnRecordWord({ id: this.learnId, userId: this.userId }).then(res => {
                    this.loading = false
                    if (res.error == 0) {
                        this.vocabularyItems = res.data
                    }
                }).finally(() => {
                    this.loading = false
                })
            }else {
                let courseId = this.course ? this.course.id : 0
                courseWordItems({ courseId: courseId, userId: this.userId }).then(res => {
                    this.loading = false
                    if (res.error == 0) {
                        this.vocabularyItems = res.data
                    }
                }).finally(() => {
                    this.loading = false
                })
            }
        },
        chooseVocabularyFun(item) {
            const index = this.selectedVocabularys.findIndex(row => row.id == item.id && row.type != 2);
            if (index !== -1) {
                this.selectedVocabularys.splice(index, 1);
            } else {
                this.selectedVocabularys.push(item)
            }
        },
        //确认选择
        async confirmChoose() {
            if (!this.selectedVocabularys.length) {
                this.$message.error('请先选择单词~')
                return
            }

            const query = {
                userId: this.userId,
                courseId: this.course.id,
            };

            this.appointmentId && (query.appointmentId = this.appointmentId);
            const { data } = await join(query);
            const nextPageRequestQuery = { userId: query.userId, courseId: query.courseId, exerciseId: data.id, words: this.selectedVocabularys.map(item => item.word), learnId: this.learnId };
            window.sessionStorage.setItem('aireading-word-next-page-request-query', JSON.stringify(nextPageRequestQuery));
            this.$router.push(`/aireading/generate?exerciseId=${data.id}&userId=${query.userId}`);
        },
        // 滚动条定位
        scrollto(id) {
            const dom = document.getElementById(id);
            if (dom && this.$refs.scrollBox) {
                this.$refs.scrollBox.scrollTo({ top: dom.offsetTop - 150, behavior: "smooth" });
            }
        },
        showVocabularys() {
            this.$refs.bearDialog.openDialog();
        },
        removeSelectedWord(index) {
            const item = this.selectedVocabularys[index] || null;
            if (item) {
                this.selectedVocabularys.splice(index, 1);
                if (item.type === 2) {
                    const _idx = this.search.ids.findIndex(id => id == item.id);
                    if (_idx !== -1) {
                        this.search.ids.splice(_idx, 1);
                    }
                }
            }
        },
        /**
         * 远程搜索数据
         * @param {*} keyword 
         */
        remoteDataMethod(keyword, init = false) {
            if (keyword || init) {
                this.search.loading = true
                getDictWordssBykeyword(keyword).then(data => {
                    this.search.loading = false
                    this.search.dataItems = data
                }).catch(() => {
                    this.search.loading = false
                })
            }
        },
        remoteDataMethodFocus(e) {
            if (!this.search.dataItems.length) {
                this.remoteDataMethod('', true)
            }
        },
        keywordChangeEvent(e) {
            this.selectedVocabularys.forEach((item, index) => {
                if (item.type == 2 && !e.includes(item.id)) {
                    this.selectedVocabularys.splice(index, 1)
                }
            });

            e.forEach(id => {
                let data = this.search.dataItems.find(row => row.id == id);
                const index = this.selectedVocabularys.findIndex(row => row.id == id && row.type == 2);
                if (data && index === -1) {
                    data = JSON.parse(JSON.stringify(data));
                    this.selectedVocabularys.push({id: data.id, type: 2, word: data.word})
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixins.scss";

.topic_cont {
    width: 100%;
    height: 100%;
    padding: 0 2.4rem;
}

.title {
    padding: 2rem 0;
    font-size: 3.2rem;
    color: #1A1A1A;
    font-weight: normal;
}

.word-item {
    font-size: 2rem;
    padding: 0.5rem 1.5rem;
    border-radius: 50px;
    border: 1px solid #e6e6e6;
}

.word-item-active {
    border: 1px solid #019E69;
    color: #fff;
    background: #019E69;
}

.el-icon-close {
    cursor: pointer;
    transition: all 0.7s;
}

.el-icon-close:hover {
    color: #de333f;
}

.search {
    // border: 1px solid $background-theme;
    // border-radius: 10px 0px 0px 10px;
    ::v-deep .el-input__inner {
        border-radius: 1rem 0px 0px 1rem !important;

    }
}

.search-box {
    width: 280px;
    position: absolute;
    right: 2rem;
    top: 2rem;

    :deep(.el-input__inner) {
        border-radius: 0rem 1rem 1rem 0rem !important;
    }

    :deep(.select-group__prepend) {
        border-radius: 1rem 0rem 0rem 1rem;
        color: #fff;
        background: $background-theme;
        border: 1px solid $background-theme;
    }
}

::v-deep .el-input-group__append {
    border-radius: 0px 1rem 1rem 0px;
    color: #fff;
    background: $background-theme;
    border: 1px solid $background-theme;

}

.search-ipt {
    width: 280px;
    border-radius: 20px;
    position: absolute;
    right: 2rem;
    top: 2rem
}

.prepend-select {
    --el-input-height: var(--el-component-size);
    --el-input-border-radius: var(--el-border-radius-base);
    --el-input-border-color: var(--el-border-color);
    
    width: 100%;
    display: inline-flex;
    align-items: stretch;
    position: relative;
    font-size: var(--el-font-size-base);
    line-height: var(--el-input-height);
    box-sizing: border-box;
    vertical-align: middle;
    border-radius: var(--el-input-border-radius);
    
    .select-group__prepend {
        font-size: 14px;
        background-color: $background-theme;
        color: #fff;
        position: relative;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-height: 100%;
        border-radius: 1rem 0rem 0rem 1rem;
        padding: 0 10px;
        white-space: nowrap;
        border-right: 0;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        box-shadow: 1px 0 0 0 var(--el-input-border-color) inset,0 1px 0 0 var(--el-input-border-color) inset,0 -1px 0 0 var(--el-input-border-color) inset;
        border: 1px solid $background-theme;
    }

    :deep(.el-select .el-input__wrapper) {
        border-left: 0;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
    }
}
</style>
